<template>
  <!-- sitekey="4bd929c1-a0e2-47ed-9950-a21b1805927c" -->
  <VueHcaptcha
    v-if="key"
    :sitekey="key"
    @verify="handleVerify"
    @error="handleError"
    ref="hcaptcha"
    size="invisible"
  />
</template>

<script setup lang="ts">
import VueHcaptcha from "@hcaptcha/vue3-hcaptcha";
import { hcaptchaValidateInfo } from "@/api/user";

const props = withDefaults(
  defineProps<{
    eventType: string;
  }>(),
  {
    eventType: "", // 埋点事件类型
  }
);
const emits = defineEmits<{
  (evt: "verify", token: string, eKey: string): void;
}>();

// firebase埋点
const firebase = useInitFirebase();

const hcaptcha = ref<any>(null);
const key = ref();

// 触发 hcaptcha
const handleExecute = () => {
  nextTick(() => {
    setTimeout(() => {
      // console.log("--hcaptcha.value--", hcaptcha.value);
      hcaptcha.value?.execute();
    }, 100);
  });
};

// 触发 reset
const handleReset = () => {
  hcaptcha.value?.reset();
  key.value = null;
  // window.hcaptcha = null;
};

const handleVerify = (token: string, eKey: string) => {
  firebase?.logEvent(`BDC_H5_${props.eventType || ""}_Verify_PUV`); // 埋点
  emits("verify", token, eKey);
};

const handleError = (err: any) => {
  firebase?.logEvent(`BDC_H5_${props.eventType || ""}_Error_PUV`); // 埋点
  console.error(err, "err");
};

const hcaptchaValidateInfoApi = async () => {
  const result = await hcaptchaValidateInfo();

  if (result.code === 200) {
    // 如果后端返回了 key，就使用后端返回的 key
    key.value = result.data?.key ?? "4bd929c1-a0e2-47ed-9950-a21b1805927c";
  } else {
    key.value = "4bd929c1-a0e2-47ed-9950-a21b1805927c";
  }
};

onMounted(() => {
  hcaptchaValidateInfoApi();
});
onBeforeUnmount(() => {
  if (hcaptcha.value) {
    hcaptcha.value.reset && hcaptcha.value.reset();
  }

  key.value = null;
});

defineExpose({
  execute: handleExecute,
  reset: handleReset,
});
</script>

<style scoped lang="scss"></style>
